//
//  PXYTabViewController.swift
//  SwitfCustomizeTabbar
//
//  Created by apple on 16/12/28.
//  Copyright © 2016年 com.zaoguankeji.www. All rights reserved.
//

import UIKit


class PXYTabViewController: UITabBarController {
    
    
fileprivate lazy var composeBtn  = UIButton.pxy_imaigeButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        
        setUpChildController()
         steupComposeBtn()
//        setUpcomposeButton()
//
        // Do any additional setup after loading the view.
    }
        override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    fileprivate func addChildViewController(_ childVc: UIViewController, title : String, imageName : String) {
        //1.设置自控制器的属性
        childVc.title = title
        childVc.tabBarItem.image = UIImage(named: imageName + "_nor")
        childVc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        //2.包装导航控制器
        let childNav = UINavigationController(rootViewController: childVc)
        //3.添加控制器
        addChildViewController(childNav)
    }
    
    @objc fileprivate func composeBtnAction(){
        print("点击撰写按钮")
    }
    
   
    
    
 }

extension UIButton {
   class func pxy_imaigeButton(_ imageName: NSString, backgroundImageName: NSString) ->UIButton {
        
        let btn  = UIButton()
        btn.setImage(UIImage(named: imageName as String), for: .normal)
        
          btn.setImage(UIImage(named: (imageName as String) + "_highlighted" as String), for: .highlighted)
        btn.setBackgroundImage(UIImage(named: backgroundImageName as String), for: .normal)
        btn.setBackgroundImage(UIImage(named: (backgroundImageName as String) + "_highlighted" as String), for: .highlighted)
        btn.sizeToFit()
        
        return btn
    }
    /*
     - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
     if (self.isHidden == NO) {
     CGPoint newP = [self convertPoint:point toView:self.addBtn];
     
     if ([self.addBtn pointInside:newP withEvent:event]) {
     return self.addBtn;
     } else {
     return [super hitTest:point withEvent:event];
     }
     } else {
     return [super hitTest:point withEvent:event];
     }
     }
     
    */
    override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        super.hitTest(point, with: event)
        return overlapHitTest(point, withEvent: event)
    }
    
   
    
}

extension UIView {
    fileprivate func overlapHitTest(_ point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        // We should not send touch events for hidden or transparent views, or views with userInteractionEnabled set to NO;
        if !self.isUserInteractionEnabled || self.isHidden || self.alpha == 0 {
            return nil
        }
        // If touch is inside self, self will be considered as potential result.
        var hitView: UIView? = self
        if !self.point(inside: point, with: event) {
            if self.clipsToBounds {
                return nil
            } else {
                hitView = nil
            }
        }
        // Check recursively all subviews for hit. If any, return it.
        for subview in self.subviews.reversed() {
            let insideSubview = self.convert(point, to: subview)
            if let sview = subview.overlapHitTest(insideSubview, withEvent: event) {
                return sview
            }
        }
        // Else return self or nil depending on result from step 2.
        return hitView as! UIButton?
    }
    
}

extension PXYTabViewController {
    
    //设置撰写按钮
    fileprivate func steupComposeBtn() {
         tabBar.addSubview(composeBtn)
        //设置位置
        let count = CGFloat(childViewControllers.count)
        // 将向内缩进宽度
        let w = tabBar.frame.width / count
        //正数 向内部缩进 、负数向外外部扩展  insetBy 左右同时往内缩小
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
//        composeBtn.frame.origin.y = -49/2
        //添加点击事件
        composeBtn.addTarget(self, action: #selector(composeBtnAction), for: .touchUpInside)
       
}
    
    fileprivate func setUpChildController() {
        
        let array = [
            ["clsName":"ViewController","title":"Home","imageName":"home"],
            ["clsName":"ViewController","title":"classify","imageName":"classify"],
            ["clsName":"UIViewcontroller"],
            ["clsName":"ViewController","title":"community","imageName":"community"],
            ["clsName":"ViewController","title":"me","imageName":"me"],
            ]
        
        var arrM = [UIViewController]()
        for dict in array {
            arrM.append(controller(dict: dict))
        }
        
        viewControllers = arrM
        
    }
    /// 使用字典创建控制器 反射
    /// - parameter dict:信息字典[clsName ,title ,imageName]
    /// - returns : 子控制器
    fileprivate func controller(dict:[String:String]) -> UIViewController {
        
        guard let clsName = dict["clsName"],
            let title = dict["title"],
            let imageName = dict["imageName"],
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
            else {
                return UIViewController()
        }
        
        let vc = cls.init()
        vc.title = title
        
        //设置图像
        vc.tabBarItem.image = UIImage(named: "tab_" + imageName + "_nor")
        vc.tabBarItem.selectedImage = UIImage(named:"tab_" + imageName + "_highlighted" )?.withRenderingMode(.alwaysOriginal)
        
        //设置字体颜色（大小）
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        //默认为 ：12
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14)], for: UIControlState(rawValue: 0))
        //2.包装导航控制器
        let childNav = UINavigationController(rootViewController: vc)
        //3.添加控制器
        addChildViewController(childNav)
        return childNav
        
    }
    

}


extension Bundle {
    
    // 计算型属性类似于函数，没有参数，有返回值
    var namespace: String {
        return infoDictionary?["CFBundleName"] as? String ?? ""
    }
}
